var ctxPath = "/mferp";
function changeBtnDisplay(elem, btn) {
    //右侧穿梭框
    var rightTransforn=$($(elem + " ul")[1]);
    // 穿梭框选中的元素
    var checkItem = rightTransforn.find('.layui-form-checked').parent();
    // 穿梭框右侧下面部分
    var rightTransBottom = rightTransforn.children();
    if(checkItem && checkItem.length == 1) {
        $(btn).removeClass("layui-btn-disabled");
        $(btn).on('click',function () {
            transferMove({
                elem : elem,
                direction : $(this).data('direction')
            });
        });
    } else {
        $(btn).addClass("layui-btn-disabled");
        $(btn).off('click');
    }
}
//layui穿梭框上移、下移功能
function transferMove(option) {
    // debugger
    //右侧穿梭框
    var rightTransforn = $($(option.elem+ " ul")[1]);
    // 穿梭框选中的元素
    var checkItem = rightTransforn.find('.layui-form-checked').parent();
    // 穿梭框右侧下面部分
    var rightTransBottom = rightTransforn.children();
    // 第一个元素的下标
    var checkOneIndex = rightTransBottom.index(option.direction=='down' ? checkItem[checkItem.length-1] : checkItem[0]);
    // 右侧有几条数据
    var rightDataLength = rightTransBottom.length;
    console.log('右侧共有', rightDataLength , '条数据');
    console.log('当前选择的元素', checkItem);
    console.log('第一个元素的下标', checkOneIndex);
    console.log('当前元素在父元素的位置', rightTransBottom.index(checkItem));
    if(!checkItem.length) {
        $news.info("请选择数据后再操作");
        return;
    }
    // 上移时，取第一个元素在父元素的位置，如果在第一位就不再移动
    if(checkOneIndex==(option.direction=='down'?rightDataLength-1:0)){
        $news.info("移不动啦");
        return;
    }
    if(option.direction == 'down') {
        for(var i = checkItem.length; i >= 0; i--){
            checkItem.eq(i).next().after(checkItem.eq(i));
        }
    } else {
        for(var i = 0;i<checkItem.length; i++){
            checkItem.eq(i).prev().before(checkItem.eq(i));
        }
    }
}
//按默认值顺序排序
function sortDefaultItem(elem, val) {
    if(!val || val.length <= 1) return;
    //右侧穿梭框
    var rightTransforn = $($(elem + " ul")[1]);
    var lis = rightTransforn.find("li");
    rightTransforn.empty();
    for(var i = 0; i < val.length; i++) {
        var v = val[i];
        lis.each(function (index, item) {
            var itemVal = String($(item).find("input").prop("value"));
            if(String(v) == itemVal) {
                rightTransforn.append($(item));
                return false;
            }
        });
    }
}
function sortByDefaultIndex(elem) {
    if(!elem) return;
    var val = ["C", "K", "F", "砂", "1-3", "1-2", "0-5", "2-4", "水", "A"];
    var exists = [];
    //右侧穿梭框
    var rightTransforn = $($(elem + " ul")[1]);
    var lis = rightTransforn.find("li");
    rightTransforn.empty();
    for(var i = 0; i < val.length; i++) {
        var v = val[i];
        lis.each(function (index, item) {
            var itemVal = String($(item).find("span").html());
            console.log(itemVal);
            if(itemVal && itemVal.indexOf(String(v)) != -1 && exists.indexOf(index) <= -1) {
                rightTransforn.append($(item));
                exists.push(index);
            }
        });
    }
    //其余材料
    lis.each(function (index, item) {
        if(exists.indexOf(index) <= -1) {
            rightTransforn.append($(item));
            exists.push(index);
        }
    });
}
var $news = {
    iframe: function (title, content, checked, success_callback, end_callback) {
        var index_ = parent.layer.open({
            title: title || '新增|编辑',
            type: 2,
            shade: 0.2,
            maxmin:true,
            shadeClose: true,
            area: ['100%', '100%'],
            content: content,
            success: function(layero, index) {
                parent.layer.setTop(layero);
                if(success_callback == null && checked != null) {
                    var body = parent.layer.getChildFrame('body', index_);
                    for(var key in checked) {
                        body.find("input[name='"+key+"']").val(checked[key]);
                    }
                    return false;
                }
                typeof success_callback === 'function' && success_callback.call(this, index);
            },
            end: function () {//无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数。layer.open关闭事件
                typeof end_callback === 'function' && end_callback.call();
            }
        });
        $(window).on("resize", function () {
            try  {
                parent.layer.full(index_);
            } catch (e) {

            }
        });
    },
    postX: function (url, data, success_callback, error_callback) {
        /*
        *   1、contentType : 'application/x-www-form-urlencoded',
        *   不能是：contentType : 'application/json'，否则后端接收到的数据为null
        *   2、data里面必须是json字符串，即var jsonStr = {"pageNum":2, "pageSize":20}格式；
        *   不能用JSON.stringify(jsonStr)来转化；否则后端接收到的数据也为null
        */
        $.ajax({
            url: ctxPath + url,
            type: 'POST',
            dataType: "json",
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            data: data,
            success: function (data) {
                typeof success_callback === 'function' && success_callback.call(this, data);
            },
            error: function (data) {
                typeof error_callback === 'function' && error_callback.call(this, data);
            }
        });
    },
    post: function (url, data, success_callback, error_callback) {
        $.ajax({
            url: ctxPath + url,
            type: 'POST',
            dataType: 'json',
            data: data,
            contentType : 'application/json;charset=UTF-8',
            success: function (data) {
                typeof success_callback === 'function' && success_callback.call(this, data);
            },
            error: function (data) {
                typeof error_callback === 'function' && error_callback.call(this, data);
            }
        });
    },
    get: function (url, data, success_callback, error_callback) {
        $.ajax({
            url: ctxPath+ url,
            type: 'GET',
            dataType: 'json',
            data: data,
            contentType: 'application/json',
            success: function (data) {
                typeof success_callback === 'function' && success_callback.call(this, data);
            },
            error: function (data) {
                typeof error_callback === 'function' && error_callback.call(this, data);
            }
        });
    },
    confirm:function (msg, callback, cancel_callback) {
        /*parent.layer.confirm(msg, {
            btn: ['确定', '取消'],
            title: "提示",
            success: function (layero, index) {
                parent.layer.close(index);
                $(document).on('keydown', function(e){
                    if(e.keyCode === 13){
                        parent.layer.close(index);
                        typeof callback === 'function' && callback.call(this);
                        $(document).off('keydown');
                    }
                });
            }
        }, function (index, layero) {
            parent.layer.close(index);
            typeof callback === 'function' && callback.call(this);
        }, function () {
            typeof cancel_callback === 'function' && cancel_callback.call(this);
        });*/
        parent.layer.confirm(msg, {
            btn: ['确定', '取消']
        }, function (index) {
            parent.layer.close(index);
            typeof callback === 'function' && callback.call(this);
        }, function (index) {
            parent.layer.close(index);
            typeof cancel_callback === 'function' && cancel_callback.call(this);
        });
    },
    open: function(area, offset, content, yesFunc) {
        parent.layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: area || ['420px', '240px'], //宽高
            offset: offset || 'auto',
            closeBtn: 1, //不显示关闭按钮
            anim: 2,
            shadeClose: true, //开启遮罩关闭
            content: content || '请填写内容',
            btn: ['确定', '取消'],
            success: function(layero, index){
                $(document).on('keydown', function(e){
                    if(e.keyCode === 13) {
                        parent.layer.close(index);
                        typeof yesFunc === 'function' && yesFunc.call();
                    }
                })
            },
            yes: function (index) {
                parent.layer.close(index);
                typeof yesFunc === 'function' && yesFunc.call();
                return false;
            },
            btn1: function (index) {
                parent.layer.close(index);
                return false;
            }
        });
    },
    success: function (msg, time, callback) {
        parent.layer.msg(msg||"操作成功", {
            icon: 6, time: (time || 3) * 1000, shadeClose: true
        }, function() {typeof callback === 'function' && callback.call(this)});
    },
    fail: function (msg, time, callback) {
        parent.layer.msg(msg||"操作失败", {
            icon: 4,time: (time || 3) * 1000, shadeClose: true
        }, function() {typeof callback === 'function' && callback.call(this)});
    },
    info: function (msg, time, callback) {
        parent.layer.msg(msg, {time: (time || 3) * 1000, shadeClose: true}, callback);
    },
    download: function (url) {
        window.open(ctxPath + url, "_blank");
    },
    transferBtn: function (option) {
        /*穿梭框选框选择事件*/
        var elem = option.elem;
        if(!elem) return;
        var btn = '.videoMoveBtn';
        var btn1 = '.videoSortBtn';
        $(elem).find(".layui-transfer-active").find("button").eq(1).css({"margin-top":"18px"});
        //添加按钮
        $(elem).find(".layui-transfer-active").prepend("<div class=\"layuiTransformBtns1\">\n" +
            "                        <button type=\"button\" data-direction=\"up\" class=\"layui-btn layui-btn-sm videoMoveBtn layui-btn-disabled\" style=\"margin-bottom: 95px;\">\n" +
            "                            <i class=\"layui-icon layui-icon-up\"></i>\n" +
            "                        </button><br>\n" +
            "                    </div>");
        $(elem).find(".layui-transfer-active").append("<div class=\"layuiTransformBtns2\">\n" +
            "                        <button type=\"button\" data-direction=\"down\" id=\"moveDown\" class=\"layui-btn layui-btn-sm videoMoveBtn layui-btn-disabled\">\n" +
            "                            <i class=\"layui-icon layui-icon-down\"></i>\n" +
            "                        </button>\n" +
            "                    </div>");
        $(elem).find(".layui-transfer-active").append("<div class=\"layuiTransformBtns3\">\n" +
            "                        <button type=\"button\" id=\"sortBtn\" class=\"layui-btn layui-btn-sm videoSortBtn\">\n" +
            "                            <i class=\"layui-icon layui-icon-flag\"></i>\n" +
            "                        </button>\n" +
            "                    </div>");
        layui.use(['transfer', 'layer', 'util', 'form'], function() {
            layui.form.on('checkbox(layTransferCheckbox)', function (data) {
                changeBtnDisplay(elem, btn);
            });
            $(btn1).on('click',function () {
                sortByDefaultIndex(elem);
            });
        });

        var val = option.val;
        console.log(val);
        if(val) {
            sortDefaultItem(elem, val);
        }
    }
};

